package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.enumeration.OperationType;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;


    //根据id查询菜品
    @Override
    public Result getById(Long id) {
        //判断id是否为空
        if (id == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //调用mapper方法查询
        Dish byId = dishMapper.getById(id);
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getDishFaloverById(id);
        DishVO vo = new DishVO();
        BeanUtils.copyProperties(byId, vo);
        vo.setFlavors(dishFlavorList);
        return Result.success(vo);
    }

    //菜品禁用启用
    @Override
    public Result updateStatus(Integer status, Long id) {
        if (id == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.updateStatus(dish);
        String pattern = "dish_" + dish.getCategoryId();
        cleanCache(pattern);
        return Result.success();
    }


    /**
     * 新增菜品
     * @param dto
     * @return
     */
    @Override
    @Transactional
    @AutoFill(OperationType.INSERT)
    public Result addDish(DishDTO dto) {
        //判断是否为空
        if (dto.getCategoryId() == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //开始新增
        Dish dish = new Dish();
        //将内容赋值过去
        BeanUtils.copyProperties(dto, dish);
        //调用方法新增菜品
        dishMapper.addDish(dish);
        //将里面的口味内容拿出来
        List<DishFlavor> flavors = dto.getFlavors();
        //设置dish的id，然后再调用dishFlavorMapper的方法将口味新增到口味表
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dish.getId());
            log.info("id", flavor.getDishId());
        }
        dishFlavorMapper.addDishFlavor(flavors);

        String pattern = "dish_" + dish.getCategoryId();
        cleanCache(pattern);

        return Result.success();
    }

    /**、
     * 修改菜品
     * @param dto
     * @return
     */
    @Override
    public Result updateDish(DishDTO dto) {
        if (dto.getId() == null) {
            return Result.error(MessageConstant.ID_NOT_EXIST);
        }
        //根据id修改dish
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.updateDish(dish);
        //直接删除所有口味再新增口味
        dishFlavorMapper.deleteDishFlavor(Arrays.asList(dto.getId()));
        //新增口味
        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dto.getId()));
            dishFlavorMapper.addDishFlavor(flavors);
        } else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //清理缓存
        String pattern = "dish_" + dish.getCategoryId();
        cleanCache(pattern);
        return Result.success();
    }


    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public Result pageQuery(DishPageQueryDTO dto) {
        //判断是否为空
        if (dto.getPage() == null) {
            dto.setPage(1);
        }
        if (dto.getPageSize() == null) {
            dto.setPageSize(10);
        }
        //使用Pagehelper开始分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        //调用方法获取total和每页的集合
        Page<Dish> page = dishMapper.pageQuery(dto);
        long total = page.getTotal();
        List<Dish> result = page.getResult();

        List<DishVO> dishVOS = new ArrayList<>();
        result.forEach(dish -> {
            DishVO dishVO = new DishVO();
            //将当前页的每页数据复制到vo里面
            BeanUtils.copyProperties(dish, dishVO);
            //根据每页数据的id查询出category里面的数组
            Category category = categoryMapper.selectById(dishVO.getCategoryId());
            //将category的名字设置到vo的名字里
            dishVO.setCategoryName(category.getName());
            //添加到
            dishVOS.add(dishVO);

        });
        //返回数据
        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setRecords(dishVOS);
        return Result.success(pageResult);
    }

    /**
     * 菜品删除
     * @param ids
     * @return
     */
    @Override
    public Result deleteBatch(List<Long> ids) {
        //判断售卖状态是否为起售状态
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //如果是起售状态则直接返回错误
                return Result.error(MessageConstant.DISH_ON_SALE);
            }
        }
        //查看有没有关联套餐，如果有就不能删除
        List<Long> setmealDishIds = setmealMapper.getSetmealByDishIds(ids);
        if (setmealDishIds != null && setmealDishIds.size() > 0) {
            return Result.error(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //如果删除菜品的话，口味也要一并删除
        dishMapper.deleteDish(ids);
        dishFlavorMapper.deleteDishFlavor(ids);
        //清理缓存
        String pattern = "dish_*";
        cleanCache(pattern);

        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public Result SelectByCategoryId(Long categoryId) {
        //判断id是否为空
        if (categoryId == null) {
            return Result.error(MessageConstant.ID_NOT_EXIST);
        }
        List<Dish> list = dishMapper.getByCategoryId(categoryId);
        //返回list
        return Result.success(list);
    }



    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> list = dishMapper.dishList(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : list) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
    //清楚缓存方法
    private void cleanCache(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
